import { getTeamUserVoByUserIdUsingGet } from '@/api/teamController'
import { defineStore } from 'pinia'
import { ref, Ref, watch, computed } from 'vue'
import { useUserStore } from './user'
import { storeToRefs } from 'pinia'

export const useTeamStore = defineStore(
  'team',
  () => {
    const userStore = useUserStore()
    const { user } = storeToRefs(userStore)

    const teamUserVoList: Ref<API.TeamUserVo[]> = ref([])
    const selectedTeam: Ref<API.TeamUserVo> = ref({})
    const myTeam = computed(
      () => teamUserVoList.value.find((team) => team.ownerId === user.value?.id) || {}
    )
    const joinedTeams = computed(() =>
      teamUserVoList.value.filter((team) => team.ownerId !== user.value?.id)
    )
    const isTeamAdmin = computed(() => {
      return user.value?.roles?.includes('admin') && selectedTeam.value?.ownerId === user.value?.id
    })

    // 监听团队列表变化
    watch(
      teamUserVoList,
      (newList) => {
        // 如果当前选中的团队在列表中，更新它的信息
        if (selectedTeam.value?.id) {
          const updatedTeam = newList.find((team) => team.id === selectedTeam.value.id)
          if (updatedTeam) {
            selectedTeam.value = updatedTeam
          } else {
            // 如果当前选中的团队不在列表中了，重置选中状态
            selectedTeam.value = newList.length > 0 ? newList[0] : {}
          }
        }
      },
      { deep: true }
    )
    // 获取团队信息,如果当前存在已选择团队，则不赋值
    async function getTeamUserVo() {
      const res: any = await getTeamUserVoByUserIdUsingGet()
      if (res.code == 0) {
        teamUserVoList.value = res.data
        // 如果当前存在已选择团队，则不赋值
        if (selectedTeam.value?.id) {
          return
        }
        if (teamUserVoList.value.length > 0) {
          selectedTeam.value = teamUserVoList.value[0]
        }
      }
    }

    // 添加更新选中团队的方法
    function updateSelectedTeam(teamId: number) {
      const team = teamUserVoList.value.find((t) => t.id === teamId)
      if (team) {
        selectedTeam.value = team
      }
    }
    // //更新团队信息后，初始化团队信息
    // async function initTeamStore() {
    //   selectedTeam.value = {}
    //   teamUserVoList.value = []
    //   await getTeamUserVo()
    // }
    return {
      teamUserVoList,
      selectedTeam,
      myTeam,
      joinedTeams,
      isTeamAdmin,
      getTeamUserVo,
      updateSelectedTeam
    }
  },
  {
    persist: true
  }
)
